package com.liu.sunnyday.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.liu.sunnyday.pojo.Permission;
import com.liu.sunnyday.pojo.Role;
import com.liu.sunnyday.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * chance！Time
 *
 * @author liuqian
 * @date 2022-07-06 12:02
 * <p>
 * 问题一：密码在那里判断这里都没有
 * q答：这里是根据用户名五表联查，将有用的都查了，
 * 返回值那里应该就是将查询到的真正密码拿去作比较
 */
@Component
public class Spring_security_UserService implements UserDetailsService {
    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名到数据库五表查询
        User user = userService.findByUsername(username);
        if (null != user) {
            //2,拿到密码(因为返回值需要)
            String password = user.getPassword();
            //3，然后创建集合存数据，遍历角色存入list
            List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();
            SimpleGrantedAuthority authority = null;

            Set<Role> roles = user.getRoles();
            if (null != roles) {
                for (Role role : roles) {
                    authority = new SimpleGrantedAuthority(role.getKeyword());
                    authorityList.add(authority);
                    //4，遍历权限存入list
                    Set<Permission> permissions = role.getPermissions();
                    if (null != permissions) {
                        for (Permission permission : permissions) {
                            authority = new SimpleGrantedAuthority(permission.getKeyword());
                            authorityList.add(authority);
                        }
                    }
                }
            }
            return new org.springframework.security.core.userdetails.User(username, password, authorityList);
        }
        return null;
    }

    /**
     * 测试BCryptPasswordEncoder加密
     */
    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // encode加密
        System.out.println(encoder.encode("1234"));
    }


}